/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jpa.controller;

import general.util.MyStringUtil;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import jpa.controller.exceptions.NonexistentEntityException;
import jpa.entity.Fornecedor;
import jpa.entity.Nota;
import jpa.entity.Pedido;
import jpa.entity.User;

/**
 *
 * @author isaias
 */
public class NotaJpaController {

    public NotaJpaController() {
        emf = Persistence.createEntityManagerFactory("ProjectObraPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Nota nota) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(nota);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Nota nota) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            nota = em.merge(nota);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = nota.getId();
                if (findNota(id) == null) {
                    throw new NonexistentEntityException("The nota with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Nota nota;
            try {
                nota = em.getReference(Nota.class, id);
                nota.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The nota with id " + id + " no longer exists.", enfe);
            }
            em.remove(nota);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Nota> findNotaForNumber(String number, User user) {
        String sql = "SELECT n FROM Nota n ";

        String where = null;

        if(user != null){
            where = " WHERE n.user.id = :id ";
        }

           if(!MyStringUtil.isNullOrEmpty(number)){
                if(MyStringUtil.isNullOrEmpty(where)){
                    where += " WHERE n.number LIKE :number ";
                }else{
                    where += " AND n.number LIKE :number ";
                }
           }

       sql +=  where;

        Query query = getEntityManager().createQuery(sql);

           if(user != null){
             query.setParameter("id", user.getId());
           }
           if(!MyStringUtil.isNullOrEmpty(number)){
              query.setParameter("number", "%" + number.toUpperCase() + "%");
           }


        try {
            return query.getResultList();
        } catch (Exception ex) {
            ex.printStackTrace();
            return new ArrayList<Nota>();
        }
    }

    public Nota findNotaForNumberAndFornecedor(String number, Fornecedor fornecedor) {
        String sql = "SELECT n FROM Nota n WHERE n.number LIKE :number AND n.fornecedor.id = :fornecedor_id";

        try {
            Query query = getEntityManager().createQuery(sql);
            query.setParameter("number", number);
            query.setParameter("fornecedor_id", fornecedor.getId());
            query.setMaxResults(1);

            return (Nota) query.getSingleResult();
        } catch (Exception ex) {
            if (!(ex instanceof NoResultException)) {
                ex.printStackTrace();
            }
            return null;
        } 
    }

    public List<Nota> findNotaEntities() {
        return findNotaEntities(true, -1, -1);
    }

    public List<Nota> findNotaEntities(int maxResults, int firstResult) {
        return findNotaEntities(false, maxResults, firstResult);
    }

    private List<Nota> findNotaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Nota.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Nota findNota(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Nota.class, id);
        } finally {
            em.close();
        }
    }

    public int getNotaCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Nota> rt = cq.from(Nota.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
